package com.huaxiafinance.management.service.impl;

import com.huaxiafinance.management.constant.CommonConstant;
import com.huaxiafinance.management.dto.request.GradeRatioDto;
import com.huaxiafinance.management.dto.request.ScoreRuleAddDto;
import com.huaxiafinance.management.dto.request.ScoreRuleDto;
import com.huaxiafinance.management.mapper.*;
import com.huaxiafinance.management.model.*;
import com.huaxiafinance.management.service.ScoreRuleService;
import com.huaxiafinance.management.util.DateUtil;
import com.huaxiafinance.management.util.MessageResult;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by huangwencheng on 2017/9/15.
 */
@Service("ScoreRuleService")
@Transactional
public class ScoreRuleServiceImpl implements ScoreRuleService {

    private static final Logger log = Logger.getLogger(ScoreRuleServiceImpl.class);

    @SuppressWarnings("SpringJavaAutowiringInspection")
    @Autowired
    private ScoreTriggerConditionMapper scoreTriggerConditionMapper;
    @SuppressWarnings("SpringJavaAutowiringInspection")
    @Autowired
    private ScoreTaskTypeMapper scoreTaskTypeMapper;
    @SuppressWarnings("SpringJavaAutowiringInspection")
    @Autowired
    private ScoreTriggerRuleMapper scoreTriggerRuleMapper;
    @SuppressWarnings("SpringJavaAutowiringInspection")
    @Autowired
    private MemberScoreGradeRatioMapper memberScoreGradeRatioMapper;
    @SuppressWarnings("SpringJavaAutowiringInspection")
    @Autowired
    private ScoreGradeMapper scoreGradeMapper;

    /**
     * 请求条件列表
     *
     * @return 触发条件列表
     */
    @Override
    public MessageResult queryScoreTriggerList() throws Exception {
        MessageResult messageResult = new MessageResult();
        List<ScoreTriggerCondition> scoreTriggerConditionList = scoreTriggerConditionMapper.queryAll();
        messageResult.setData(scoreTriggerConditionList);
        messageResult.setSuccessResult();
        return messageResult;
    }

    /**
     * 请求积分类型列表
     *
     * @return 积分类型列表
     */
    @Override
    public MessageResult queryScoreTaskList() throws Exception {
        MessageResult messageResult = new MessageResult();
        List<ScoreTaskType> scoreTaskTypeList = scoreTaskTypeMapper.queryAll();
        messageResult.setData(scoreTaskTypeList);
        messageResult.setSuccessResult();
        return messageResult;
    }

    /**
     * 请求触发规则列表
     *
     * @param dto 请求参数
     * @return 触发规则列表
     */
    @Override
    public MessageResult queryScoreTriggerRules(ScoreRuleDto dto) throws Exception {
        MessageResult messageResult = new MessageResult();
        //分页
        if (dto.getRows()==null||dto.getPage()==null){
            dto.setPage(CommonConstant.PAGE);
            dto.setRows(CommonConstant.ROWS);
        }else {
            dto.setPage(dto.getPage() * dto.getRows());
        }
        //查询所有规则
        List<ScoreTriggerRule> scoreTriggerRuleList = scoreTriggerRuleMapper.queryScoreRules(dto);
        //统计条数
        int countScoreRuleNum = scoreTriggerRuleMapper.countScoreRules(dto);
        messageResult.setRows(countScoreRuleNum);
        messageResult.setData(scoreTriggerRuleList);
        messageResult.setSuccessResult();
        return messageResult;
    }

    /**
     * 请求积分规则详情
     *
     * @param dto 请求参数
     * @return 返回积分详情
     */
    @Override
    public MessageResult queryScoreRuleDetails(ScoreRuleDto dto) throws Exception {
        MessageResult messageResult = new MessageResult();
        //判断请求参数
        if (dto.getId()==null){
            messageResult.setFailureResult("请重新请求");
            return messageResult;
        }
        //查询积分规则详情
        ScoreTriggerRule scoreTriggerRule = scoreTriggerRuleMapper.selectById(dto);
        List<MemberScoreGradeRatio> memberScoreGradeRatioList = new ArrayList<MemberScoreGradeRatio>();
        if (scoreTriggerRule != null) {
            //查询会员列表详情
            memberScoreGradeRatioList = memberScoreGradeRatioMapper.queryMemberScoreList(scoreTriggerRule.getId());
        }else {
            scoreTriggerRule = new ScoreTriggerRule();
        }
        scoreTriggerRule.setMemberScoreGradeRatioList(memberScoreGradeRatioList);
        messageResult.setData(scoreTriggerRule);
        messageResult.setSuccessResult();
        return messageResult;
    }

    /**
     * 检查规则是否已编辑
     *
     * @param dto 请求参数
     * @return 返回检查结果
     */
    @Override
    public MessageResult inspectRuleName(ScoreRuleDto dto) throws Exception {
        MessageResult messageResult = new MessageResult();
        if (dto.getTriggerId()==null){
            messageResult.setFailureResult("请重新请求");
            return messageResult;
        }
        ScoreTriggerRule scoreTriggerRule = scoreTriggerRuleMapper.selectByRuleId(dto);
        if (scoreTriggerRule != null) {
            messageResult.setResultCode("8100");
            messageResult.setMsg("已经拥有该规则");
        } else {
            messageResult.setSuccessResult();
        }
        return messageResult;
    }

    /**
     * 新增积分触发规则
     *
     * @param dto 请求参数
     * @return 返回新增结果
     */
    @Override
    public MessageResult insertScoreRule(ScoreRuleAddDto dto) throws Exception {
        MessageResult messageResult = new MessageResult();
        //判断规则是否增加过
        ScoreRuleDto scoreRuleDto = new ScoreRuleDto();
        scoreRuleDto.setTriggerId(dto.getTriggerId());
        ScoreTriggerRule scoreTriggerRule = scoreTriggerRuleMapper.selectByRuleId(scoreRuleDto);
        if (scoreTriggerRule!=null){
            messageResult.setFailureResult("该规则已经添加");
            return messageResult;
        }
        synchronized (this) {
            scoreTriggerRule = scoreTriggerRuleMapper.selectNumber();
            String triggerNumberStr = null;
            if (scoreTriggerRule == null) {
                dto.setTriggerNumber(CommonConstant.TRIGGER_NUMBER);
                triggerNumberStr = dto.getTriggerNumber();
            } else {
                String triggerNumber = scoreTriggerRule.getTriggerNumber();
                int number = Integer.parseInt(triggerNumber == null ? CommonConstant.TRIGGER_NUMBER : triggerNumber) + 1;
                triggerNumberStr = String.format("%02d", number);
            }
            //判断时间
            Date startDate = null;
            Date endDate = null;
            if (dto.getStartDate() != null&&!("").equals(dto.getStartDate())) {
               startDate = DateUtil.getStart(dto.getStartDate());
            }
            if (dto.getEndDate() != null&&!("").equals(dto.getEndDate())) {
                endDate = DateUtil.getEnd(dto.getEndDate());
            }
            scoreTriggerRule = new ScoreTriggerRule();
            //插入数据
            scoreTriggerRule.setComment(dto.getComment());
            scoreTriggerRule.setGmtCreate(new Date());
            scoreTriggerRule.setGmtModified(new Date());
            scoreTriggerRule.setStartDate(startDate);
            scoreTriggerRule.setEndDate(endDate);
            scoreTriggerRule.setTaskStyleId(dto.getTaskStyleId());
            scoreTriggerRule.setTriggerId(dto.getTriggerId());
            scoreTriggerRule.setScore(dto.getScore());
            scoreTriggerRule.setTriggerNumber(triggerNumberStr);
            //插入规则
            int n = scoreTriggerRuleMapper.insertSelective(scoreTriggerRule);
            if (n < 1) {
                messageResult.setFailureResult();
                return messageResult;
            }
            //查询规则id
            scoreTriggerRule = scoreTriggerRuleMapper.selectByTriggerNumberStr(triggerNumberStr);
            //插入积分会员倍数规则
            List<GradeRatioDto> gradeRatioList = dto.getMemberScoreGradeRatioList();
            MemberScoreGradeRatio memberScoreGradeRatio = new MemberScoreGradeRatio();
            memberScoreGradeRatio.setRuleId(scoreTriggerRule.getId());
            for (GradeRatioDto gradeRatioDto : gradeRatioList) {
                memberScoreGradeRatio.setGradeId(gradeRatioDto.getGradeId());
                memberScoreGradeRatio.setGradeRatio(gradeRatioDto.getGradeRatio());
                memberScoreGradeRatio.setGmtCreate(new Date());
                memberScoreGradeRatio.setGmtModified(new Date());
                int i = memberScoreGradeRatioMapper.insertSelective(memberScoreGradeRatio);
                if (i < 1) {
                    messageResult.setFailureResult();
                    return messageResult;
                }
            }
        }
        messageResult.setSuccessResult();
        return messageResult;
    }

    /**
     * 修改规则
     *
     * @param dto 修改规则请求参数
     * @return 修改成功
     */
    @Override
    public MessageResult updateScoreRule(ScoreRuleAddDto dto) throws Exception {
        MessageResult messageResult = new MessageResult();
        ScoreTriggerRule scoreTriggerRule = scoreTriggerRuleMapper.selectByPrimaryKey(dto.getId());
        //判断时间
        if (dto.getStartDate() != null&&!("").equals(dto.getStartDate())) {
            Date startDate = DateUtil.getStart(dto.getStartDate());
            scoreTriggerRule.setStartDate(startDate);
        }
        if (dto.getEndDate() != null&&!("").equals(dto.getEndDate())) {
            Date endDate = DateUtil.getEnd(dto.getEndDate());
            scoreTriggerRule.setEndDate(endDate);
        }
        if (("").equals(dto.getStartDate())){
            scoreTriggerRule.setStartDate(null);
        }
        if (("").equals(dto.getEndDate())){
            scoreTriggerRule.setEndDate(null);
        }
        scoreTriggerRule.setComment(dto.getComment());
        scoreTriggerRule.setScore(dto.getScore());
        scoreTriggerRule.setTaskStyleId(dto.getTaskStyleId());
        scoreTriggerRule.setTriggerId(dto.getTriggerId());
        scoreTriggerRule.setGmtModified(new Date());
        //修改规则
        int n = scoreTriggerRuleMapper.updateScoreTriggerRule(scoreTriggerRule);
        if (n < 1) {
            messageResult.setFailureResult();
            return messageResult;
        }
        //插入积分会员倍数规则
        List<GradeRatioDto> gradeRatioList = dto.getMemberScoreGradeRatioList();
        MemberScoreGradeRatio memberScoreGradeRatio = new MemberScoreGradeRatio();
        memberScoreGradeRatio.setRuleId(scoreTriggerRule.getId());
        for (GradeRatioDto gradeRatioDto : gradeRatioList) {
            //判断id不能为空
            if (gradeRatioDto.getId()==null){
                messageResult.setFailureResult("积分会员id不能为空");
                return messageResult;
            }
            memberScoreGradeRatio.setGradeId(gradeRatioDto.getGradeId());
            memberScoreGradeRatio.setGradeRatio(gradeRatioDto.getGradeRatio());
            memberScoreGradeRatio.setGmtModified(new Date());
            memberScoreGradeRatio.setId(gradeRatioDto.getId());
            int i = memberScoreGradeRatioMapper.updateByPrimaryKeySelective(memberScoreGradeRatio);
            if (i < 1) {
                messageResult.setFailureResult();
                return messageResult;
            }
        }

        messageResult.setSuccessResult();
        return messageResult;
    }

    /**
     * 请求积分等级基础数据
     * @return 积分等级基础数据
     */
    @Override
    public MessageResult queryScoreGrade() throws Exception {
        MessageResult messageResult = new MessageResult();
        List<ScoreGrade> scoreGradeList = scoreGradeMapper.queryAll();
        messageResult.setData(scoreGradeList);
        messageResult.setSuccessResult();
        return messageResult;
    }

    /**
     * 删除积分规则
     * @return 积分等级基础数据
     */
    @Override
    public MessageResult deleteScoreRule(ScoreRuleDto dto) throws Exception {
        MessageResult messageResult = new MessageResult();
        //判断是否传id
        if (dto.getId()==null){
            messageResult.setFailureResult("请重新请求");
            return messageResult;
        }
        int n = scoreTriggerRuleMapper.updateById(dto.getId());
        if (n<1){
            messageResult.setFailureResult("请重新请求");
            return messageResult;
        }
        messageResult.setSuccessResult();
        return messageResult;
    }
}
